package com.endpoint.member.controller;

import com.endpoint.common.bean.UserDetails;
import com.endpoint.common.utils.HttpUtils;
import com.endpoint.common.utils.ResultBean;
import com.endpoint.member.config.OAuth2Config;
import com.endpoint.member.service.OAuth2Service;
import com.endpoint.member.vo.SocialUserVo;
import com.endpoint.member.vo.UserInfoVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Project: endpoint
 * @Name: OAuth2Controller
 * @Author: Jack_Li
 * @Date: 2024/7/6 13:11
 */

@Slf4j
@Api(tags = "社交登录相关接口")
@Controller
@RequestMapping("/member/oauth2")
public class OAuth2Controller {

    @Resource
    private OAuth2Service oAuth2Service;

    @Autowired
    private OAuth2Config oAuth2Config;


//    @RequestMapping("/redirect")
//    public ResultBean github(@NotEmpty String code) throws Exception {
//
//        log.info("code:{}", code);
//
//        String redirectHome = "http://localhost:9999/home";
//
//        String path = oAuth2Config.getGithubPath()
//                .replace("clientId", oAuth2Config.getGithubClientId())
//                .replace("clientSecret", oAuth2Config.getGithubClientSecret())
//                .replace("authorize_code", code);
//        HttpResponse get = HttpUtils.doGet(
//                oAuth2Config.getGithubHost(),
//                path,
//                "GET",
//                new HashMap<String, String>(),
//                new HashMap<String, String>());
//        if (get.getStatusLine().getStatusCode() == 200) {
//            //如果返回状态码是200 执行成功了
//            //获取返回的授权令牌  通过方法将返回的令牌对象 转为 json格式字符串
//            String result = EntityUtils.toString(get.getEntity());
//            log.info("result：{}", result);
//            String accessToken = null;
//            Pattern p = Pattern.compile("=(\\w+)&");
//            Matcher m = p.matcher(result);
//            while (m.find()) {
//                accessToken = m.group(1);
//                log.info("令牌token：{}", m.group(1));
//                break;
//            }
//
//
//            String userInfoHost = oAuth2Config.getGithubGetUserInfoHost();
//            String userInfoPath = oAuth2Config.getGithubGetUserInfoPath();
//            log.info("url：{}", userInfoHost + userInfoPath);
//            HashMap<String, String> headers = new HashMap<>();
//            headers.put("Authorization", "token " + accessToken);
//            HttpResponse response = HttpUtils.doGet(userInfoHost, userInfoPath, "GET", headers, new HashMap<String, String>());
//            String userResult = EntityUtils.toString(response.getEntity());
//
//            log.info("userResult：{}", userResult);
//
//            UserInfoVo userVo = new ObjectMapper().readValue(userResult, UserInfoVo.class);
//            log.info("userVo：{}", userVo);
//            SocialUserVo socialUserVo = new SocialUserVo();
//            socialUserVo.setUid(userVo.getId());
//            socialUserVo.setIsRealName(userVo.getName());
//            socialUserVo.setAvatar_url(userVo.getAvatar_url());
//            socialUserVo.setAccess_token(accessToken);
//            UserDetails userDetails = oAuth2Service.oauthLogin(socialUserVo);
//            ModelAndView mv = new ModelAndView(new RedirectView(redirectHome));
//            mv.addObject("userDetails", userDetails);
//            return ResultBean.ok(oAuth2Service.oauthLogin(socialUserVo));
//        }
//        return ResultBean.ok();
//    }

    @RequestMapping("/redirect")
    public ModelAndView github(@NotEmpty String code) throws Exception {

        log.info("code:{}", code);

        String redirectHome = "http://localhost:9999/#/home";

        String path = oAuth2Config.getGithubPath()
                .replace("clientId", oAuth2Config.getGithubClientId())
                .replace("clientSecret", oAuth2Config.getGithubClientSecret())
                .replace("authorize_code", code);
        HttpResponse get = HttpUtils.doGet(
                oAuth2Config.getGithubHost(),
                path,
                "GET",
                new HashMap<String, String>(),
                new HashMap<String, String>());
        if (get.getStatusLine().getStatusCode() == 200) {
            //如果返回状态码是200 执行成功了
            //获取返回的授权令牌  通过方法将返回的令牌对象 转为 json格式字符串
            String result = EntityUtils.toString(get.getEntity());
            log.info("result：{}", result);
            String accessToken = null;
            Pattern p = Pattern.compile("=(\\w+)&");
            Matcher m = p.matcher(result);
            while (m.find()) {
                accessToken = m.group(1);
                log.info("令牌token：{}", m.group(1));
                break;
            }


            String userInfoHost = oAuth2Config.getGithubGetUserInfoHost();
            String userInfoPath = oAuth2Config.getGithubGetUserInfoPath();
            log.info("url：{}", userInfoHost + userInfoPath);
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Authorization", "token " + accessToken);
            HttpResponse response = HttpUtils.doGet(userInfoHost, userInfoPath, "GET", headers, new HashMap<String, String>());
            String userResult = EntityUtils.toString(response.getEntity());

            log.info("userResult：{}", userResult);

            UserInfoVo userVo = new ObjectMapper().readValue(userResult, UserInfoVo.class);
            log.info("userVo：{}", userVo);
            SocialUserVo socialUserVo = new SocialUserVo();
            socialUserVo.setUid(userVo.getId());
            socialUserVo.setIsRealName(userVo.getName());
            socialUserVo.setAvatar_url(userVo.getAvatar_url());
            socialUserVo.setAccess_token(accessToken);
            UserDetails userDetails = oAuth2Service.oauthLogin(socialUserVo);
            ModelAndView mv = new ModelAndView(new RedirectView(redirectHome));
            mv.addObject("userDetails", userDetails);
            redirectHome += "?uid=" + userVo.getId();
            return new ModelAndView(new RedirectView(redirectHome));
        }
        redirectHome = "http://localhost:9999/login";
        return new ModelAndView(new RedirectView(redirectHome));
    }

}
